package convertutil

import (
	"bytes"
	"encoding/xml"
	"strings"
)

func XmlToMap(xmlStr string) map[string]string {
	params := make(map[string]string)
	decoder := xml.NewDecoder(strings.NewReader(xmlStr))
	var key, value string
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch token := t.(type) {
		case xml.StartElement: // 开始标签
			key = token.Name.Local
		case xml.CharData: // 标签内容
			value = strings.TrimSpace(string(token))
		}
		if key != "xml" && value != "" {
			params[key] = value
		}
	}
	return params
}

func MapToXml(params map[string]string) string {
	var buf bytes.Buffer
	buf.WriteString(`<xml>`)
	for k, v := range params {
		buf.WriteString(`<`)
		buf.WriteString(k)
		buf.WriteString(`><![CDATA[`)
		buf.WriteString(v)
		buf.WriteString(`]]></`)
		buf.WriteString(k)
		buf.WriteString(`>`)
	}
	buf.WriteString(`</xml>`)
	return buf.String()
}
